package com.fancy.learncenter.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonAnswerKeysBean;
import com.fancy.learncenter.bean.CartoonAnswersBean;
import com.fancy.learncenter.bean.CartoonCommitAnswerBean;
import com.fancy.learncenter.bean.CartoonFillBlankBean;
import com.fancy.learncenter.bean.CartoonGetAnswerResultBean;
import com.fancy.learncenter.bean.CartoonGetHomeAnswerBean;
import com.fancy.learncenter.bean.CartoonMediaBean;
import com.fancy.learncenter.bean.CartoonStemsBean;
import com.fancy.learncenter.bean.CartoonTextsBean;
import com.fancy.learncenter.bean.CheckDoQuestion;
import com.fancy.learncenter.bean.QuestionVOsBean;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.MAudioPlayer;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.CartoonWorkQuestionTypeActivity;
import com.fancy.learncenter.ui.adapter.CustomTagAdapter;
import com.fancy.learncenter.ui.callback.KeyboardViewImpl;
import com.fancy.learncenter.ui.view.CartoonAnalysisPopu;
import com.fancy.learncenter.ui.view.CustomKeyboardView;
import com.fancy.learncenter.utils.CartoonToastUtils;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagFlowLayout;
import com.zhy.view.flowlayout.TagView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

import static com.fancy.learncenter.common.JumpIntentKey.OPTION_STATUS.STATUS_CHOOSE;
import static com.fancy.learncenter.common.JumpIntentKey.OPTION_STATUS.STATUS_DEFAULT;
import static com.fancy.learncenter.common.JumpIntentKey.OPTION_STATUS.STATUS_RIGHT;
import static com.fancy.learncenter.common.JumpIntentKey.OPTION_STATUS.STATUS_WORD;
import static com.fancy.learncenter.common.JumpIntentKey.OPTION_STATUS.STATUS_WRONG;
import static com.fancy.learncenter.common.JumpIntentKey.RIGHT_NUM;

/**
 * 单词类------看图听音拼写
 */
public class WordSeeImageListenSpellNewFragment extends MyBaseFragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @Bind(R.id.commit_image)
    ImageView commitImage;
    @Bind(R.id.previous_question)
    ImageView previousQuestion;
    @Bind(R.id.next_question)
    ImageView nextQuestion;
    @Bind(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @Bind(R.id.voice_image)
    ImageView voiceImage;
    @Bind(R.id.question_image)
    SimpleDraweeView questionImage;
    @Bind(R.id.flowlayout)
    TagFlowLayout flowlayout;
    @Bind(R.id.invisible_view)
    View invisibleView;
    @Bind(R.id.scrollView)
    ScrollView scrollView;
    @Bind(R.id.keyboard_view)
    CustomKeyboardView keyboardView;
    // TODO: Rename and change types of parameters
    private int currentIndex;
    private int totalNum;
    private String questionStr;
    private String imageUrl;
    private String audioStr;
    private OnWordSeeImageListenSpellListener mListener;
    private String titleStr;
    private JumpIntentKey.QUESTION_ENTER_TYPE type;
    private List<CartoonFillBlankBean> blankList;
    private String homePackageId;
    private QuestionVOsBean questionVOsBean;
    private CustomTagAdapter tagAdapter;
    private List<String> standardAnswerList; //标准答案
    private List<String> writeAnswerList; //填写答案
    private List<CartoonCommitAnswerBean> commitAnswerList; //提交答案
    private int state;
    private String studentHomeworkId;
    private Fragment currentFragment;
    private String analysisText;
    private Handler handler = new Handler();
    private JumpIntentKey.CARTOON_BUTTON_STATUS buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_GRAY;
    private MAudioPlayer audioPlayer;
    private String lessonNameStr;
    private String unitNameStr;

    public WordSeeImageListenSpellNewFragment() {
        // Required empty public constructor
    }

    @Override
    public String fmCallBackName() {
        return titleStr;
    }

    /**
     *
     */
    // TODO: Rename and change types and number of parameters
    public static WordSeeImageListenSpellNewFragment newInstance(QuestionVOsBean list, int currentIndex, int totalNum, JumpIntentKey.QUESTION_ENTER_TYPE type,
                                                                 String homePackageId, String studentHomeworkId, String lessonNameStr, String unitNameStr) {
        WordSeeImageListenSpellNewFragment fragment = new WordSeeImageListenSpellNewFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, currentIndex);
        args.putInt(ARG_PARAM2, totalNum);
        args.putParcelable(JumpIntentKey.QUSETION_BANK_LIST_KEY, list);
        args.putSerializable(JumpIntentKey.QUESTION_ENTER, type);
        args.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
        args.putString(JumpIntentKey.STUDENTHOMEWORKID, studentHomeworkId);
        args.putString(JumpIntentKey.LESSON_NAME, lessonNameStr);
        args.putString(JumpIntentKey.UNIT_NAME, unitNameStr);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentFragment = this;
        if (getArguments() != null) {
            currentIndex = getArguments().getInt(ARG_PARAM1);
            totalNum = getArguments().getInt(ARG_PARAM2);

            questionVOsBean = getArguments().getParcelable(JumpIntentKey.QUSETION_BANK_LIST_KEY);

            type = (JumpIntentKey.QUESTION_ENTER_TYPE) getArguments().getSerializable(JumpIntentKey.QUESTION_ENTER);
            homePackageId = getArguments().getString(JumpIntentKey.HOMEWORK_PACKAGE_ID);
            studentHomeworkId = getArguments().getString(JumpIntentKey.STUDENTHOMEWORKID);
            lessonNameStr = getArguments().getString(JumpIntentKey.LESSON_NAME);
            unitNameStr = getArguments().getString(JumpIntentKey.UNIT_NAME);

            if (doQusValue.equals(NO_DO_SUBMMIT)) {
                checkQuestionIsDone();
            }


        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_word_see_image_listen_spell_new, container, false);
        ButterKnife.bind(this, view);
        initData();
        initClick();
        return view;
    }


    private void initData() {

        CartoonStemsBean stemsBean = questionVOsBean.getStems();


        titleStr = questionVOsBean.getConstructionNameCn();

        if (stemsBean != null) {
            List<CartoonTextsBean> textsBeans = stemsBean.getTexts();
            List<CartoonMediaBean> imageBeans = stemsBean.getImages();
            List<CartoonMediaBean> audioBean = stemsBean.getAudios();


            if (imageBeans != null && imageBeans.get(0) != null) {

                imageUrl = imageBeans.get(0).getImgUrl();

            } else {
//                imageUrl = imageBeans.get(0).getImgUrl();
//                voiceImage.setVisibility(View.GONE);
                imageUrl = "";
                questionImage.setVisibility(View.GONE);
            }

            audioStr = audioBean.get(0).getPlayLink();
            questionStr = "";
            for (int i = 0; i < textsBeans.size(); i++) {
                questionStr = questionStr + textsBeans.get(i).getValue();
            }

        }

        CartoonAnswerKeysBean answerKeysBean = questionVOsBean.getAnswerKeys();
        if (answerKeysBean != null) {
            List<CartoonTextsBean> answerKeysList = answerKeysBean.getTexts();
            if (answerKeysList != null && answerKeysList.size() > 0) {
                analysisText = "";
                for (int i = 0; i < answerKeysList.size(); i++) {
                    analysisText = analysisText + answerKeysList.get(i).getValue();
                }
            }
        }

        CartoonAnswersBean answersBean = questionVOsBean.getAnswers();
        standardAnswerList = new ArrayList<String>();
        if (answersBean != null) {
            List<CartoonTextsBean> textsBeanList = answersBean.getTexts();
            if (textsBeanList != null) {
                for (int i = 0; i < textsBeanList.size(); i++) {
                    CartoonTextsBean textsBean = textsBeanList.get(i);
                    standardAnswerList.add(textsBean.getValue());
                }
            }
        }
        questionImage.setImageURI(imageUrl);
        String[] strArray = questionStr.split(" ");
        blankList = new ArrayList<>();
        for (int i = 0; i < strArray.length; i++) {

            CartoonFillBlankBean blankBean = new CartoonFillBlankBean();
            blankBean.setStatus(STATUS_DEFAULT);
            blankBean.setValue(strArray[i]);
            CartoonFillBlankBean blankBean2 = new CartoonFillBlankBean();
            blankBean2.setStatus(STATUS_DEFAULT);
            blankBean2.setValue(" ");
//            blankBean.setValue(String.valueOf(questionStr.charAt(i)));
            blankList.add(blankBean);
            blankList.add(blankBean2);
        }

        tagAdapter = new CustomTagAdapter(getActivity(), blankList, type);
        flowlayout.setAdapter(tagAdapter);

        flowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {

                switch (type) {

                    case DO_WORK:
                    case CONTINUE_WORK:
                    case DO_IT_AGAIN:
                    case HAS_CORRECTED:
                    case NOT_CORRECTED:
                    case ERROR_KINDS:
                        break;
                    case WORK_REPORT:
                        return true;
                    case NO_CLICK:
                        return true;
                }

                TagView tagView = (TagView) view;
                RelativeLayout linearLayout = (RelativeLayout) tagView.getTagView();
                TextView textView = (TextView) linearLayout.getChildAt(0);
                if (blankList.get(position).getValue().equals("##")) {
                    switch (blankList.get(position).getStatus()) {
                        case STATUS_DEFAULT:
                            blankList.get(position).setStatus(STATUS_CHOOSE);
                            break;
                        case STATUS_CHOOSE:
                            break;
                        case STATUS_WORD:
                            blankList.get(position).setStatus(STATUS_CHOOSE);
                            break;
                    }

                    for (int i = 0; i < blankList.size(); i++) {
                        if (i != position && blankList.get(i).getValue().equals("##")) {
                            if (blankList.get(i).getStatus() == STATUS_CHOOSE) {
                                if (!TextUtils.isEmpty(blankList.get(i).getOptionValue())) {
                                    blankList.get(i).setStatus(STATUS_WORD);
                                } else {
                                    blankList.get(i).setStatus(STATUS_DEFAULT);
                                }
                            }
                        }
                    }

                    tagAdapter.notifyDataChanged();


                    invisibleView.setVisibility(View.VISIBLE);
                    keyboardView.setVisibility(View.VISIBLE);
                    scrollView.fullScroll(View.FOCUS_DOWN);

                    textView.setBackgroundResource(R.mipmap.cartoon_white_dot);


                    if (NO_DO_SUBMMIT.equals(doQusValue)) {
                        onButtonPressed(true, Integer.parseInt(NO_DO_SUBMMIT));
                        buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_LIGHT;
                    }


                }
                return true;
            }
        });
    }

    @Override
    public String fmCallBackValue() {
        return doQusValue;
    }

//    class CustomTagAdapter extends TagAdapter<CartoonFillBlankBean> {
//        JumpIntentKey.QUESTION_ENTER_TYPE type;
//        public CustomTagAdapter(List<CartoonFillBlankBean> datas, JumpIntentKey.QUESTION_ENTER_TYPE type) {
//            super(datas);
//            this.type = type;
//        }
//
//        @Override
//        public View getView(FlowLayout parent, int position, CartoonFillBlankBean item) {
//            RelativeLayout view = (RelativeLayout) LayoutInflater.from(getActivity()).inflate(R.layout.question_name_item_layout, flowlayout, false);
//            final TextView question = (TextView) view.findViewById(R.id.question_letter);
//
//
//
//
//            if ("##".equals(item.getValue())) {
//                switch (item.getStatus()) {
//                    case STATUS_DEFAULT:
//                        question.setText("");
//                        view.setBackgroundResource(R.mipmap.cartoon_transparent_word);
//                        break;
//                    case STATUS_CHOOSE:
//                        if (!TextUtils.isEmpty(item.getOptionValue())){
//                            question.setText(item.getOptionValue());
//                            question.setGravity(Gravity.CENTER);
//                        }else {
//                            question.setText("");
//                        }
//                        view.setBackgroundResource(R.mipmap.cartoon_white_dot);
//                        break;
//                    case STATUS_WORD:
//                        if (!TextUtils.isEmpty(item.getOptionValue())) {
//                            question.setText(item.getOptionValue());
//                        }
//                        view.setBackgroundResource(R.mipmap.cartoon_white_dot);
//                        break;
//
//                    case STATUS_WRONG:
//                        if (!TextUtils.isEmpty(item.getOptionValue())) {
//                            question.setText(item.getOptionValue());
//                        }
//                        view.setBackgroundResource(R.mipmap.cartoon_word_error);
//                        break;
//
//                    case STATUS_RIGHT:
//                        if (!TextUtils.isEmpty(item.getOptionValue())) {
//                            question.setText(item.getOptionValue());
//                        }
//                        view.setBackgroundResource(R.mipmap.cartoon_word_right);
//                        break;
//
//                }
//
//            } else {
//                question.setText(item.getValue());
//                question.setBackground(null);
//            }
//
//
//            return view;
//        }
//    }


    private void initClick() {

        switch (type) {
            case DO_WORK:
            case CONTINUE_WORK:
                previousQuestion.setVisibility(View.GONE);
                nextQuestion.setVisibility(View.GONE);
                break;
            case DO_IT_AGAIN:
                previousQuestion.setVisibility(View.GONE);
                nextQuestion.setVisibility(View.GONE);
                break;
            case WORK_REPORT:
                previousQuestion.setVisibility(View.VISIBLE);
                nextQuestion.setVisibility(View.VISIBLE);
                if (currentIndex == 0) {
                    previousQuestion.setVisibility(View.GONE);
                }
                if (currentIndex == totalNum - 1) {
                    nextQuestion.setVisibility(View.GONE);
                }
                getWorkReportAnswer();
                break;
            case HAS_CORRECTED:
            case NOT_CORRECTED:
            case ERROR_KINDS:
                previousQuestion.setVisibility(View.VISIBLE);
                nextQuestion.setVisibility(View.VISIBLE);
                if (currentIndex == 0) {
                    previousQuestion.setVisibility(View.GONE);
                }
                if (currentIndex == totalNum - 1) {
                    nextQuestion.setVisibility(View.GONE);
                }

                break;
            case TEACHER_WORK_PREVIEW:

                flowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                    @Override
                    public boolean onTagClick(View view, int position, FlowLayout parent) {
                        return false;
                    }
                });
                seeAnswer();
                break;
        }

        commitImage.setEnabled(false);
        commitImage.setOnClickListener(this);
        previousQuestion.setOnClickListener(this);
        nextQuestion.setOnClickListener(this);
        voiceImage.setOnClickListener(this);
        keyboardView.setKeyboardClick(new KeyboardViewImpl() {
            @Override
            public void onClick(String keyValue) {


                for (int i = 0; i < blankList.size(); i++) {

                    if (blankList.get(i).getStatus() == STATUS_CHOOSE) {
                        if (!TextUtils.isEmpty(blankList.get(i).getOptionValue())) {
                            ToastUtil.show("请先删除");
                            return;
                        }
                        blankList.get(i).setOptionValue(keyValue);
                        isShowCommitButton();
                        tagAdapter.notifyDataChanged();
                        break;
                    }
                }

            }

            @Override
            public void deleteClick() {

                for (int i = 0; i < blankList.size(); i++) {

                    if (blankList.get(i).getStatus() == STATUS_CHOOSE) {
                        if (!TextUtils.isEmpty(blankList.get(i).getOptionValue())) {
                            blankList.get(i).setOptionValue("");
                            isShowCommitButton();
                            tagAdapter.notifyDataChanged();
                            return;
                        }

                        break;
                    }
                }
            }

            @Override
            public void okClick() {

                keyboardView.setVisibility(View.GONE);
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.voice_image:
                Utils.playOrPauseAudio(audioPlayer, audioStr, voiceImage);
                break;
            case R.id.commit_image:
                switch (buttonStatus) {
                    case STATUS_LIGHT:
                        judgeRightOrWrong();
                        switch (type) {
                            case DO_WORK:
                            case CONTINUE_WORK:
                            case DO_IT_AGAIN:
                            case HAS_CORRECTED:
                                commitAnswer();
                                break;
                            case NOT_CORRECTED:
                            case ERROR_KINDS:
                                if (state == 1) {
                                    errorQuestionCommitAnswer();
                                } else {
                                    errorBusniessLogic();
                                }
                                break;
                        }
                        break;
                    case STATUS_SEE_ANSWER:
                        seeAnswer();
                        break;
                    case STATUS_ANALYSIS:
                        CartoonAnalysisPopu popu = new CartoonAnalysisPopu(getActivity(), analysisText, commitImage);
                        popu.showPopupWindow();
                        break;
                }

                break;

//            case R.id.previous_question:
//                FragmentTransaction transaction = getFragmentManager().beginTransaction();
//                Utils.switchFragment(getActivity(), transaction, questionList, currentIndex - 1, R.id.fg_container, type,
//                        homePackageId, studentHomeworkId,lessonNameStr,unitNameStr);
//                break;
//            case R.id.next_question:
//                FragmentTransaction transaction2 = getFragmentManager().beginTransaction();
//                Utils.switchFragment(getActivity(), transaction2, questionList, currentIndex + 1, R.id.fg_container, type,
//                        homePackageId, studentHomeworkId,lessonNameStr,unitNameStr);
//
//                break;


        }
    }

    /**
     * 查看答案
     */
    private void seeAnswer() {
        for (int i = 0; i < blankList.size(); i++) {

            if ("##".equals(blankList.get(i).getValue())) {
                if (standardAnswerList != null && standardAnswerList.size() > 0) {
                    blankList.get(i).setOptionValue(standardAnswerList.get(0));
                    blankList.get(i).setStatus(STATUS_RIGHT);
                    standardAnswerList.remove(0);
                }
            }
        }

        tagAdapter.notifyDataChanged();

        buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_ANALYSIS;

        if (getActivity() instanceof CartoonWorkQuestionTypeActivity) {
            Utils.notifyButtonBg(buttonStatus, ((CartoonWorkQuestionTypeActivity) getActivity()).getCommitImage());
        }

    }


    /**
     * 获取客观题答案
     */
    private void getWorkReportAnswer() {

        Map<String, Object> map = new HashMap<>();
        map.put("packageId", homePackageId);
        map.put("classId", MyApplication.classIDStr);
        map.put("questionId", questionVOsBean.getQuestionId());

        HttpMehtod.getInstance().cartoonGetHomeAnswer(map, new CustomNetSubscriber(getActivity(), false) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonGetAnswerResultBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonGetAnswerResultBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonGetAnswerResultBean>() {
                    @Override
                    public void success(CartoonGetAnswerResultBean dataBean) {

                        if (dataBean != null) {
                            CartoonGetHomeAnswerBean homeAnswerBean = dataBean.getResult();
                            List<CartoonCommitAnswerBean> answerResourceList = homeAnswerBean.getAnswerResourceList();
                            List<String> tempList = new ArrayList<>();
                            for (CartoonCommitAnswerBean bean : answerResourceList) {
                                tempList.add(bean.getResourceValue());
                            }

                            if (Utils.compare(tempList, standardAnswerList)) {
                                commitImage.setVisibility(View.INVISIBLE);

                                buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_HIDE;
                            } else {

                                buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_SEE_ANSWER;
                                Utils.notifyButtonBg(buttonStatus, commitImage);
                            }

                            List<String> tempAnswerList = new ArrayList<>();
                            tempAnswerList.addAll(standardAnswerList);

                            for (int i = 0; i < blankList.size(); i++) {

                                if ("##".equals(blankList.get(i).getValue())) {
                                    if (tempList != null && tempList.size() > 0 && tempAnswerList != null && tempAnswerList.size() > 0) {
                                        if (tempList.get(0).equals(tempAnswerList.get(0))) {
                                            blankList.get(i).setStatus(STATUS_RIGHT);
                                        } else {
                                            blankList.get(i).setStatus(STATUS_WRONG);
                                        }
                                        tempAnswerList.remove(0);
                                        blankList.get(i).setOptionValue(tempList.get(0));
                                        tempList.remove(0);
                                    }

                                }
                            }

                            tagAdapter.notifyDataChanged();


                            if (isUserShow) {
                                if (type == JumpIntentKey.QUESTION_ENTER_TYPE.WORK_REPORT) {

                                    if (getActivity() instanceof CartoonWorkQuestionTypeActivity) {
                                        Utils.notifyButtonBg(buttonStatus, ((CartoonWorkQuestionTypeActivity) getActivity()).getCommitImage());
                                    }

                                }
                            }

                        }

                    }

                    @Override
                    public void fail(String errorCode) {


                    }
                }).dealData();
            }
        });

    }


    /**
     * 是否显示提交按钮
     */
    private void isShowCommitButton() {
        writeAnswerList = new ArrayList<>();
        for (int i = 0; i < blankList.size(); i++) {
            if ("##".equals(blankList.get(i).getValue()) && !TextUtils.isEmpty(blankList.get(i).getOptionValue())) {
                writeAnswerList.add(blankList.get(i).getOptionValue());
            }
        }

        int totalStandardNum = standardAnswerList.size();
        int writeNum = writeAnswerList.size();
        Log.i("num_standard_num", totalStandardNum + "");
        Log.i("num_write", writeNum + "");
        if (totalStandardNum == writeNum) {
            buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_LIGHT;
            Utils.notifyButtonBg(buttonStatus, commitImage);
        } else {
            buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_GRAY;
            Utils.notifyButtonBg(buttonStatus, commitImage);
        }
    }

    private void judgeRightOrWrong() {
        doQusValue = DO_SUBMMIT;
        if (Utils.compare(writeAnswerList, standardAnswerList)) {
            RIGHT_NUM++;
            state = 1;
        } else {
            state = 0;
            if (type == JumpIntentKey.QUESTION_ENTER_TYPE.NOT_CORRECTED || type == JumpIntentKey.QUESTION_ENTER_TYPE.ERROR_KINDS) {
                doQusValue = NO_DO_SUBMMIT;
            }
        }
    }

    private void jumpToFragement(final int index) {

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                onButtonPressed(true, Integer.parseInt(DO_SUBMMIT));
            }
        }, CartoonWorkQuestionTypeActivity.JUMP_FRG_TIME);

    }

    /**
     * 错题中心里面，错误后，查看答案 解析 等逻辑
     */
    private void errorBusniessLogic() {

        buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_SEE_ANSWER;
//        Utils.notifyButtonBg(buttonStatus, commitImage);

        if (getActivity() instanceof CartoonWorkQuestionTypeActivity) {
            Utils.notifyButtonBg(buttonStatus, ((CartoonWorkQuestionTypeActivity) getActivity()).getCommitImage());
        }

        List<String> tempAnswerList = new ArrayList<>();
        List<String> tempList = new ArrayList<>();
        tempAnswerList.addAll(standardAnswerList);
        tempList.addAll(writeAnswerList);
        for (int i = 0; i < blankList.size(); i++) {

            if ("##".equals(blankList.get(i).getValue())) {
                if (writeAnswerList != null && writeAnswerList.size() > 0 && tempAnswerList != null && tempAnswerList.size() > 0) {
                    if (tempList.get(0).equals(tempAnswerList.get(0))) {
                        blankList.get(i).setStatus(STATUS_RIGHT);
                    } else {
                        blankList.get(i).setStatus(STATUS_WRONG);
                    }
                    tempAnswerList.remove(0);
                    blankList.get(i).setOptionValue(tempList.get(0));
                    tempList.remove(0);
                }

            }
        }

        tagAdapter.notifyDataChanged();

    }


    /**
     * 提交答案
     */
    private void commitAnswer() {

        if (writeAnswerList == null) {
            return;
        }
        judgeRightOrWrong();
        commitAnswerList = new ArrayList<>();
        for (int i = 0; i < writeAnswerList.size(); i++) {
            CartoonCommitAnswerBean answerBean = new CartoonCommitAnswerBean();
            answerBean.setResourceType("0");
            answerBean.setResourceValue(writeAnswerList.get(i));
            commitAnswerList.add(answerBean);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("classId", MyApplication.classIDStr);
        map.put("state", state);
        map.put("homeworkPackageId", homePackageId);
        map.put("objectQuestionId", questionVOsBean.getQuestionId());
        map.put("answerResourceList", commitAnswerList);
        map.put("studentHomeworkId", studentHomeworkId);
        HttpMehtod.getInstance().cartoonCommitHomeAnsers(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                switch (type) {
                    case HAS_CORRECTED:
                    case NOT_CORRECTED:
                    case ERROR_KINDS:
                        if (state == 1) {
                            jumpToFragement(0);
                        } else {
                            errorBusniessLogic();
                        }
                        break;

                    case DO_WORK:
                    case CONTINUE_WORK:
                    case DO_IT_AGAIN:
                        jumpToFragement(0);

                        break;
                }

                if (state == 1) {
                    CartoonToastUtils.show(true);
                } else {
                    CartoonToastUtils.show(false);
                }

            }
        });

    }

    /**
     * 错题中心 -- 未订正 错题分类
     */
    private void errorQuestionCommitAnswer() {
        Map<String, Object> map = new HashMap<>();
        map.put("studentHomeworkDoneDetailId", questionVOsBean.getStudentHomeworkDoneDetailId());
        HttpMehtod.getInstance().cartoonCorrectErrorQuestion(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                jumpToFragement(currentIndex + 1);

            }
        });
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(boolean isDo) {
        if (mListener != null) {
            mListener.onWordSeeImageListenSpell(isDo, 0, "");
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(boolean isDo, int num) {
        if (mListener != null) {
            mListener.onWordSeeImageListenSpell(isDo, num, "");
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnWordSeeImageListenSpellListener) {
            mListener = (OnWordSeeImageListenSpellListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void fmCallBack() {
        switch (buttonStatus) {
            case STATUS_LIGHT:

                switch (type) {
                    case DO_WORK:
                    case CONTINUE_WORK:
                    case DO_IT_AGAIN:
                    case HAS_CORRECTED:
                        commitAnswer();
                        break;
                    case NOT_CORRECTED:
                    case ERROR_KINDS:
                        judgeRightOrWrong();

                        if (state == 1) {
                            CartoonToastUtils.show(true);
                        } else {
                            CartoonToastUtils.show(false);
                        }

                        if (state == 1) {
                            errorQuestionCommitAnswer();
                        } else {
                            errorBusniessLogic();
                        }
                        break;
                }
                break;
            case STATUS_SEE_ANSWER:
                seeAnswer();
                break;
            case STATUS_ANALYSIS:
                CartoonAnalysisPopu popu = new CartoonAnalysisPopu(getActivity(), analysisText, commitImage);
                popu.showPopupWindow();
                break;
        }

    }

    /**
     *
     */
    public interface OnWordSeeImageListenSpellListener {
        // TODO: Update argument type and name
        void onWordSeeImageListenSpell(boolean isDo, int totalNum, String title);
    }

    /**
     */
    private void checkQuestionIsDone() {
        if (type == JumpIntentKey.QUESTION_ENTER_TYPE.TEACHER_WORK_PREVIEW) {
            return;
        }
        if (type == JumpIntentKey.QUESTION_ENTER_TYPE.DO_IT_AGAIN) {
            return;
        }
        if (type == JumpIntentKey.QUESTION_ENTER_TYPE.NOT_CORRECTED) {
            return;
        }
        if (type == JumpIntentKey.QUESTION_ENTER_TYPE.HAS_CORRECTED) {
            return;
        }
        if (type == JumpIntentKey.QUESTION_ENTER_TYPE.ERROR_KINDS) {
            return;
        }
        if (type == JumpIntentKey.QUESTION_ENTER_TYPE.WORK_REPORT) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("studentHomeworkId", studentHomeworkId);
        map.put("questionId", questionVOsBean.getQuestionId());
        HttpMehtod.getInstance().checkQuestionIsDone(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CheckDoQuestion> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CheckDoQuestion.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CheckDoQuestion>() {
                    @Override
                    public void success(CheckDoQuestion dataBean) {


                        if (dataBean.isIsDone()) {
                            doQusValue = "0";
                        } else {
                            doQusValue = "1";
                        }
                        LogUtil.MyLog("checkQuestionIsDone", "==checkQuestionIsDone==" + dataBean.isIsDone());
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });
    }

    /**
     * 0 已提交
     * <p>
     * 1 未提交
     */
    public String doQusValue = NO_DO_SUBMMIT;


    boolean isFirst = true;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        LogUtil.MyLog("CartoonPicSpeakFragment", "=====setUserVisibleHint===" + isVisibleToUser);

        if (!isVisibleToUser) {

            if (type != JumpIntentKey.QUESTION_ENTER_TYPE.WORK_REPORT) {
                if (questionImage != null) {
                    initData();
                }
            }


            isFirst = false;
            if (questionVOsBean != null) {
                if (NO_DO_SUBMMIT.equals(doQusValue)) {
                    checkQuestionIsDone();
                } else {

                }
            }

            isUserShow = false;

            if (audioPlayer != null && audioPlayer.isPlaying()) {
                audioPlayer.pause();
            }
        } else {
            if (keyboardView != null) {
                keyboardView.setVisibility(View.GONE);
            }
            isUserShow = true;
            if (type == JumpIntentKey.QUESTION_ENTER_TYPE.WORK_REPORT) {

                if (getActivity() instanceof CartoonWorkQuestionTypeActivity) {
                    Utils.notifyButtonBg(buttonStatus, ((CartoonWorkQuestionTypeActivity) getActivity()).getCommitImage());
                }

            }
        }


        super.setUserVisibleHint(isVisibleToUser);
    }

    boolean isUserShow = false;
}
